package dao;

import model.*;

import java.util.List;

/**
 * 查询维修状态，物业费时具体数据库操作类，并生成要返回的后端处理状态码
 * Created by jcala on 2016/3/16.
 */
public class StatesOperator implements ConcreteOperatorInter {
    private CheckBean bean;
    private UpdateQuery uq=null;
    private StatesBean allData=null;
    private int[] ids=null;
    public StatesOperator(CheckBean bean) {
        this();
        this.bean=bean;
        uq=new UpdateQuery();
    }
    private StatesOperator() {
    }
    /**
     * @return 根据操作状态生成的最终状态码
     */
    @Override
    public int operate() {
        int result=150;
        ids=getInfo();
        if(ids[0]>0||ids[1]>0){
            PropertyBean property=getProperty(ids[0]);
            List<FixBean> list=getFixes(ids[1]);
            if((property!=null)||(list!=null&&list.size()>0)){
                allData =new StatesBean(property,list);
                return 151;
            }
        }
        return 150;
    }

    /**
     * 查询数据库得到用户表中的fixid和propertyid
     * @return
     */
    private int[] getInfo(){
        String sql="select fixid from user where username=?";
        String sql1="select propertyid from user where username=?";
        String username=bean.getUsername();
        int fixid=-1;
        int propertyid=-1;
        int[] ii=new int[2];
        try {
            fixid=uq.getforvalue(sql,4,username);
            propertyid=uq.getforvalue(sql1,4,username);
            ii[0]=fixid;
            ii[1]=propertyid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ii;
    }

    /**
     *通过得到的propertyid查询property表，得到相应的包含物业费信息的javabean
     * @param id 上面方法得到的fixid
     * @return 保存物业信息的PropertyBean
     */
   private PropertyBean getProperty(int id){
       PropertyBean bean=null;
       String sql="select * from property where id=?";
       try {
           Class claz=Class.forName("model.PropertyBean");
           bean=(PropertyBean)uq.get(claz,sql,id);
       } catch (Exception e) {
           e.printStackTrace();
       }
       return bean;
   }
    /**
     *通过得到的fixid查询fix表，得到相应的包含维修信息的javabean
     * @param id 上面方法得到的fixid
     * @return 保存物业信息的FixBean的集合
     */
    private List<FixBean> getFixes(int id){
        List<FixBean> fixes=null;
        String sql="select * from fix where id=?";
        try {
            Class claz=Class.forName("model.FixBean");
            fixes=(List<FixBean>)uq.getForList(claz,sql,id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fixes;
    }

    public StatesBean getAllData() {
        return allData;
    }
}
